package breeze.lepei.der.main_view.view;

import android.app.ActivityOptions;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import breeze.lepei.der.BaseView;
import breeze.lepei.der.R;
import breeze.lepei.der.loginview.view.LoginView;
import breeze.lepei.der.logo_view.model.BackDataModel;
import breeze.lepei.der.main_view.model.LastedExamModel;
import breeze.lepei.der.main_view.model.StuHisAdapter;
import breeze.lepei.der.main_view.model.StuHistoryExamModel;
import breeze.lepei.der.main_view.presenter.IMainPresenter;
import breeze.lepei.der.main_view.presenter.MainPresenter;
import breeze.lepei.der.usersettings.UserSettings;
import breeze.lepei.der.utils.AppSettings;
import breeze.lepei.der.utils.AppTools;
import breeze.lepei.der.utils.MDialog;
import breeze.lepei.der.utils.MLog;
import breeze.lepei.der.view.barchartview.view.BarChartView;
import java.util.List;
import android.support.v7.widget.LinearLayoutManager;

public class MainView extends BaseView implements IMainView,OnClickListener,NavigationView.OnNavigationItemSelectedListener {

	
	/**
	*@author BREEZE
	*@description 设置列表
	*@param 信息
	*/
	@Override
	public void setRecyclerData(final List<StuHistoryExamModel.Obj> data) {
		runOnUiThread(new Runnable(){public void run(){
			StuHisAdapter adapter=new StuHisAdapter(MainView.this,data);
			ExamHistory.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
			ExamHistory.setAdapter(adapter);
		}});
	}
	
	/**
	*@author BREEZE
	*@description 设置最新考试信息
	*@param 最新考试数据
	*/
	@Override
	public void setLastedExam(final LastedExamModel data) {
		runOnUiThread(new Runnable(){public void run(){
		if("200".equals(data.getCode())){
			//TODO：获取信息成功
			LastedExamModel.Obj obj=data.getObj();
			if(obj.getState()==1){
				//有数据信息
				ExamName.setText(obj.getExamName());
				StringBuilder sb=new StringBuilder();
				sb.append("学校最高").append(String.valueOf(obj.getSchoolHighScore())).append("分，")
				.append("学校均分").append(String.valueOf(obj.getSchoolAvgScore())).append("分，")
				.append(obj.getStudentName()).append("（考号："+obj.getExamNo()+"）")
				.append("得分").append(String.valueOf(obj.getScore())).append("，学校排名").append(String.valueOf(obj.getSchoolRank())).append("名。");
				ExamInfo.setText(sb);
			}else{
				ExamName.setText(obj.getExamName());
				ExamInfo.setText("—成绩还未公布—");
			}
		}else{
			showDialog("获取最新考试失败",data.getMsg());
		}
		}});
	}
	
	/**
	*@author BREEZE
	*@description 登录
	*/
	@Override
	public void login() {
		presenter.login(user_sets.getUserPhone(),user_sets.getUserPass());
	}

	/**
	*@author BREEZE
	*@description 显示数据
	*@param UserSettings
	*/
	@Override
	public void setStudentInfo(final UserSettings sets) {
		runOnUiThread(new Runnable(){public void run(){
			tv_StudentName.setText(sets.getStudentName());
			tv_SchoolName.setText(sets.getSchoolName());
			tv_Grade.setText(sets.getGrade()+sets.getClassName());
			btn_MoreInfo.setEnabled(true);
			//获取成绩
			presenter.getStudentLastedExam();
			//获取统计图
			chartView.init(MainView.this);
			//获取历史考试
			presenter.getStudentHisExam();
		}});
	}

	/**
	*@author BREEZE
	*@description 提示bug
	*@param 错误
	*/
	@Override
	public void showAppBug(Exception exception) {
		showDialog("运行错误",exception.toString());
	}

	/**
	*@author BREEZE
	*@description 展示软件公告
	*/
	@Override
	public void showAppNotice() {
		BackDataModel backdata=BackDataModel.getInstance(this);
		final AppSettings appsets=AppSettings.getInstance(this);
		final String an=backdata.getAnnouncement();
		if(!appsets.getNotice().equals(an)){
			MLog.log(TAG,"显示公告：",an);
			final MDialog dialog=new MDialog(this);
			dialog.setTitle("公告");
			dialog.setMessage(an); 
			dialog.setPositiveButton("确定",null);
			dialog.setNegativeBotton("不再提醒",new OnClickListener(){
					@Override
					public void onClick(View p1) {
						appsets.setNotice(an);
						dialog.dismiss();
					}
				});
			dialog.show();
		}
	}

	/**
	*@author BREEZE
	*@description 显示对话框
	*@param 标题/内容
	*/
	@Override
	public void showDialog(final String title,final String message) {
		runOnUiThread(new Runnable(){public void run(){
				MDialog.show(MainView.this,title,message);
		}});
	}

	@Override
	public boolean onNavigationItemSelected(MenuItem p1) {
		switch(p1.getItemId()){
			case R.id.menu_main_charity:
				//TODO：捐赠
				presenter.showCharity(this);
				break;
			case R.id.menu_main_join_qq:
				//TODO：加人QQ群
				presenter.joinQQGroup(this,"lepIXINtLxsva0DmS0JXS7ogRmEaNc0E");
				break;
			case R.id.menu_main_reset_password:
				//TODO：修改密码
				presenter.showResetPassword(this);
				break;
			case R.id.menu_main_logout:
				//TODO：登出
				user_sets.logOut();
				startActivity(new Intent(this,LoginView.class),ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
				finish();
				break;
			case R.id.menu_main_about:
				//TODO：版本信息
				showDialog("关于软件",AppTools.getVersionInfo(this));
				break;
		}
		return true;
	}

	@Override
	public void initTypeFace() {
		Typeface english=Typeface.createFromAsset(getAssets(),"font/eng.ttf");
		Typeface chinese=Typeface.createFromAsset(getAssets(),"font/chi.ttf");
		View headerView=mNavigationView.inflateHeaderView(R.layout.view_main_navigation_header);
		((TextView)headerView.findViewById(R.id.view_main_navigation_headerTextView)).setTypeface(english);
		tv_StudentName.setTypeface(chinese);
		tv_SchoolName.setTypeface(chinese);
		tv_Grade.setTypeface(chinese);
		tv_sign.setTypeface(chinese);
	}

	@Override
	public void onClick(View p1) {
		switch(p1.getId()){
			case R.id.main_std_info_more_btn:
				//TODO：学生更多信息
				StringBuilder sb=new StringBuilder();
				sb.append("学生ID：").append(user_sets.getStudentId()).append("\n")
				.append("学生RID：").append(user_sets.getRid()).append("\n")
				.append("班级ID：").append(user_sets.getClassCode()).append("\n")
				.append("学生名称：").append(user_sets.getStudentName()).append("\n")
				.append("学校名称：").append(user_sets.getSchoolName()).append("\n")
				.append("学生年级：").append(user_sets.getGrade()).append("\n")
				.append("学生班级：").append(user_sets.getClassName());
				showDialog("学生信息",sb.toString());
				break;
			case R.id.main_head_img:
				//TODO：获取头像
				presenter.getQQDialog(img_HeadImage,this);
				break;
			case R.id.main_tv_sign:
				//TODO：查看公告
				showDialog("乐培通知",user_sets.getNotice());
				break;
		}
	}

	@Override
	public void init() {
		mNavigationView=f(R.id.main_NavigationView);
		mDrawerLayout=f(R.id.main_DrawerLayout);
		toolbar=f(R.id.toolbar);
		img_HeadImage=f(R.id.main_head_img);
		img_HeadImage.setOnClickListener(this);
		tv_SchoolName=f(R.id.main_school_name_tv);
		tv_StudentName=f(R.id.main_student_name_tv);
		tv_Grade=f(R.id.main_grade_name_tv);
		btn_MoreInfo=f(R.id.main_std_info_more_btn);
		btn_MoreInfo.setOnClickListener(this);
		tv_sign=f(R.id.main_tv_sign);
		tv_sign.setOnClickListener(this);
		ExamName=f(R.id.view_main_exam_name);
		ExamInfo=f(R.id.view_main_exam_infomation);
		chartView=f(R.id.view_main_BarChartView);
		ExamHistory=f(R.id.view_main_info_RecyclerView);
	}

	@Override
	public void initData() {
		user_sets=UserSettings.getInstance(this);
		presenter=new MainPresenter(this);
		login();
		//TODO：获取头像
		if(!"".equals(user_sets.getQQ())){
			presenter.getHeadImg(img_HeadImage,user_sets.getQQ());
		}
		//TODO：获取公告
		presenter.getNotice(tv_sign);
		toolbar.setTitle("培个Der");
		toolbar.setNavigationIcon(R.drawable.ic_menu);
		setSupportActionBar(toolbar);
		toolbar.setNavigationOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View p1) {
					presenter.openDrawerLayout(mDrawerLayout);
				}
		});
		mNavigationView.inflateMenu(R.menu.menu_main_drawerlayout);
		mNavigationView.setItemIconTintList(null);
		mNavigationView.setItemTextColor(ColorStateList.valueOf(getColor("#000000")));
		mNavigationView.setNavigationItemSelectedListener(this);
	}
    
    public static final String TAG = "MainView";
	private NavigationView mNavigationView;
	private Toolbar toolbar;
	private DrawerLayout mDrawerLayout;
	private IMainPresenter presenter;
	private UserSettings user_sets;
	private ImageView img_HeadImage;//头像
	private TextView tv_StudentName,tv_SchoolName,tv_Grade,tv_sign,ExamName,ExamInfo;
	private Button btn_MoreInfo;
	private BarChartView chartView;
	private RecyclerView ExamHistory;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getWindow().setEnterTransition(new Slide());
		fitSystemStatusBar(getColor("#009688"));
		setContentView(R.layout.view_main);
		init();
		initData();
		initTypeFace();
		showAppNotice();
    }

	/**
	*@author BREEZE
	*@description 点击两次返回
	*/
	private boolean isExit=false;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==event.KEYCODE_BACK){
			if(!isExit){
				toast("再按一次退出");
				isExit=true;
				exitHandler.sendEmptyMessageDelayed(0,2000);
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	Handler exitHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			isExit=false;
			super.handleMessage(msg);
		}
	};
    
}
